package com.wei.duowan.bbs.ui.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.constraint.Group;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.google.gson.Gson;
import com.wei.duowan.bbs.App;
import com.wei.duowan.bbs.R;
import com.wei.duowan.bbs.contract.INewsFunction;
import com.wei.duowan.bbs.model.ArticleBean;
import com.wei.duowan.bbs.model.CommentBean;
import com.wei.duowan.bbs.model.NewsBean;
import com.wei.duowan.bbs.model.NewsDetailBean;
import com.wei.duowan.bbs.model.NewsTypeBean;
import com.wei.duowan.bbs.model.RelatedBean;
import com.wei.duowan.bbs.model.VideoInfoBean;
import com.wei.duowan.bbs.presenter.BasePresenter;
import com.wei.duowan.bbs.ui.adapter.BaseDelegateAdapter;
import com.wei.duowan.bbs.ui.adapter.BaseViewHolder;
import com.wei.duowan.bbs.ui.adapter.NewsContentAdapter;
import com.wei.duowan.bbs.widget.ShareUtils;
import com.wei.duowan.bbs.utils.StringUtils;
import com.wei.duowan.bbs.utils.TimeUtils;

import butterknife.Bind;
import butterknife.OnClick;

import static android.text.TextUtils.isEmpty;

/**
 * 作者：赵若位
 * 时间：2019/8/27 22:38
 * 联系方式：1070138445
 * 功能：头条详情页
 */
public class NewsActivity extends BaseActivity implements INewsFunction
{
    private static final String TAG = NewsActivity.class.getSimpleName();

    @Bind(R.id.tv_comment)
    TextView mTvComment;
    @Bind(R.id.tv_send)
    TextView mTvSend;
    @Bind(R.id.group_menu)
    Group mGroupMenu;
    @Bind(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private DelegateAdapter mAdapter;
    /*文章内容*/
    private NewsContentAdapter mArticleAdapter;
    /*文章标题*/
    private BaseDelegateAdapter mArticleTitleAdapter;
    /*文章推荐标题*/
    private BaseDelegateAdapter mRecommendTitleAdapter;
    /*文章推荐*/
    private BaseDelegateAdapter mRecommendAdapter;
    /*评论标题*/
    private BaseDelegateAdapter mCommentsTitleAdapter;
    /*评论*/
    private BaseDelegateAdapter mCommentsAdapter;

    /*视频标题*/
    private BaseDelegateAdapter mVideoAdapter;
    /*视频推荐标题*/
    private BaseDelegateAdapter mRelatedTitleAdapter;
    /*视频推荐*/
    private BaseDelegateAdapter mRelatedAdapter;


    private NewsBean mNewsBean;
    private NewsDetailBean mData;

    /*分享*/
    private ShareUtils mShareUtils;


    @Override
    protected BasePresenter createPresenter()
    {
        return null;
    }

    @Override
    protected int getLayoutID()
    {
        return R.layout.activity_news;
    }

    @Override
    protected void initView()
    {
        setFinish();
        VirtualLayoutManager manager = new VirtualLayoutManager(this);
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        mRecyclerView.setLayoutManager(manager);
        mAdapter = new DelegateAdapter(manager, false);
        mRecyclerView.setAdapter(mAdapter);
//        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
//        {
//            @Override
//            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState)
//            {
//                if (newState == RecyclerView.SCROLL_STATE_IDLE)
//                {
//                    if (this != null)
//                    {
//                        GlideApp.with(NewsActivity.this).resumeRequests();//恢复Glide加载图片
//                    }
//                } else
//                {
//                    if (this != null)
//                    {
//                        GlideApp.with(NewsActivity.this).pauseRequests();//禁止Glide加载图片
//                    }
//                }
//            }
//        });

        mNewsBean = getIntent().getParcelableExtra(TAG);
        Log.e(TAG, "initView: " + mNewsBean.getAdSrc());

        switch (mNewsBean.getShowType())
        {
            case NewsTypeBean.PICTURE:
                mData = null;
                break;
            case NewsTypeBean.VIDEO:
                mData = new Gson().fromJson(StringUtils.getAssetsJson("头条详情-视频.json"), NewsDetailBean.class);
                break;
            default:
                mData = new Gson().fromJson(StringUtils.getAssetsJson("头条详情-1.json"), NewsDetailBean.class);
                break;
        }
        setNewAdapter(mData);

        setNewData(mData);
    }


    private void setNewAdapter(@Nullable NewsDetailBean data)
    {
        mAdapter.clear();

        if (data.getArticle() != null)
        {
            mAdapter.addAdapter(getArticleTitleAdapter());
            mAdapter.addAdapter(getArticleAdapter());
        }

        if (data.getVideoInfo() != null)
        {
            mAdapter.addAdapter(getVideoAdapter());
        }

        if (data.getRecommend() != null && data.getRecommend().size() != 0)
        {
            mAdapter.addAdapter(getRecommendTitleAdapter());
            mAdapter.addAdapter(getRecommendAdapter());
        }

        if (data.getRelated() != null)
        {
            mAdapter.addAdapter(getRelatedTitleAdapter());
            mAdapter.addAdapter(getRelatedAdapter());
        }

        //添加评论
        mAdapter.addAdapter(getCommentsTitleAdapter());
        mAdapter.addAdapter(getCommentsAdapter());
    }


    private void setNewData(@Nullable NewsDetailBean data)
    {
        if (data.getArticle() != null)
        {
            getArticleTitleAdapter().setNewData(data.getArticle());
            getArticleAdapter().setNewData(StringUtils.getArticleContent(data.getArticle().getContent().trim()));
        }

        if (data.getVideoInfo() != null)
        {
            getVideoAdapter().setNewData(data.getVideoInfo());
        }

        if (data.getRecommend() != null && data.getRecommend().size() != 0)
        {
            getRecommendTitleAdapter().setNewData(getString(R.string.related_recommended));
            getRecommendAdapter().setNewData(data.getRecommend());
        }

        if (data.getRelated() != null && data.getRelated().size() != 0)
        {
            getRelatedTitleAdapter().setNewData(getString(R.string.related_video));
            getRelatedAdapter().setNewData(data.getRelated());
        }

        String json = StringUtils.getAssetsJson("头条详情-评论.json");
        CommentBean comments = new Gson().fromJson(json, CommentBean.class);
        mCommentsTitleAdapter.setNewData(comments);
        mCommentsAdapter.setNewData(comments.getComment());
    }


    @OnClick({R.id.img_action, R.id.img_share, R.id.img_fav, R.id.img_comment, R.id.tv_send})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.img_action://分享
                share();
                break;
            case R.id.img_share://分享:
                share();
                break;
            case R.id.img_fav://收藏
                break;
            case R.id.img_comment://评论
                //TODO 滚动至评论标题
                break;
            case R.id.tv_send://发布
                break;
        }
    }


    /*文章标题*/
    public BaseDelegateAdapter getArticleTitleAdapter()
    {
        if (mArticleTitleAdapter == null)
        {
            //标题
            mArticleTitleAdapter = new BaseDelegateAdapter<ArticleBean>(this, R.layout.layout_news_title)
            {
                @Override
                protected void convert(@Nullable BaseViewHolder holder, int position, @Nullable ArticleBean data)
                {
                    StringBuffer buffer = new StringBuffer();
                    buffer.append(getString(R.string.source))
                            .append(":")
                            .append(isEmpty(data.getDigest()) ? getString(R.string.unknown) : data.getDigest())
                            .append("  ")
                            .append(getString(R.string.author))
                            .append(":")
                            .append(data.getAuthor())
                            .append("  ")
                            .append(TimeUtils.getNewsTime(data.getPublishTime() * 1000));
                    holder.setText(R.id.tv_title, data.getTitle())
                            .setText(R.id.tv_descript, buffer.toString());
                }
            };
        }
        return mArticleTitleAdapter;
    }


    /*文章内容*/
    public NewsContentAdapter getArticleAdapter()
    {
        if (mArticleAdapter == null)
        {
            mArticleAdapter = new NewsContentAdapter(this);
        }
        return mArticleAdapter;
    }

    /*文章推荐*/
    public BaseDelegateAdapter getRecommendTitleAdapter()
    {
        if (mRecommendTitleAdapter == null)
        {
            mRecommendTitleAdapter = new BaseDelegateAdapter<String>(this, R.layout.layout_news_recommended)
            {
                @Override
                protected void convert(@Nullable BaseViewHolder holder, int position, @Nullable String data)
                {
                    holder.setText(R.id.tv_title, data);
                }
            };
        }
        return mRecommendTitleAdapter;
    }

    /*推荐*/
    public BaseDelegateAdapter getRecommendAdapter()
    {
        if (mRecommendAdapter == null)
        {
            mRecommendAdapter = new BaseDelegateAdapter<NewsBean>(this, R.layout.layout_news)
            {
                @Override
                protected void convert(@Nullable BaseViewHolder holder, int position, @Nullable NewsBean data)
                {
                    holder.setVisibility(R.id.img_game, isEmpty(data.getPictureUrl()) ? View.GONE : View.VISIBLE)
                            .setImageResource(R.id.img_game, isEmpty(data.getPictureUrl()) ? "" : data.getPictureUrl())
                            .setText(R.id.tv_title, data.getTitle())
                            .setText(R.id.tv_time, TimeUtils.getNewsTime(data.getPublishTime() * 1000))
                            .setText(R.id.tv_count, isEmpty(data.getComment()) ? "0" : data.getComment());
                }
            };
        }
        return mRecommendAdapter;
    }


    /*视频*/
    public BaseDelegateAdapter getVideoAdapter()
    {
        if (mVideoAdapter == null)
        {
            mVideoAdapter = new BaseDelegateAdapter<VideoInfoBean>(this, R.layout.layout_news_video)
            {
                @Override
                protected void convert(@Nullable BaseViewHolder holder, int position, @Nullable VideoInfoBean data)
                {
                    holder.setImageResource(R.id.img, "http://img.dwstatic.com/df/1902/413979455569/1550024584996.jpg")
                            .setText(R.id.tv_title, data.getVideo_title())
                            .setText(R.id.tv_author, data.getVideo_intro())
                            .setText(R.id.tv_count, data.getVideo_play_num())
                            .setCircleResource(R.id.img_nickname, data.getUser_avatar())
                            .setText(R.id.tv_time, data.getVideo_upload_time())
                            .setText(R.id.tv_nickname, data.getUser_nickname())
                            .setOnClickListener(R.id.tv_download, new View.OnClickListener()
                            {
                                @Override
                                public void onClick(View view)
                                {
                                    downloadVideo();
                                }
                            });
                }
            };
        }
        return mVideoAdapter;
    }


    /*视频推荐标题*/
    public BaseDelegateAdapter getRelatedTitleAdapter()
    {
        if (mRelatedTitleAdapter == null)
        {
            mRelatedTitleAdapter = new BaseDelegateAdapter<String>(this, R.layout.layout_news_related)
            {
                @Override
                protected void convert(@Nullable BaseViewHolder holder, int position, @Nullable String s)
                {
                    holder.setText(R.id.tv_title, s);
                }
            };
        }
        return mRelatedTitleAdapter;
    }


    /*视频推荐*/
    private BaseDelegateAdapter getRelatedAdapter()
    {
        if (mRelatedAdapter == null)
        {
            mRelatedAdapter = new BaseDelegateAdapter<RelatedBean>(this, R.layout.layout_news)
            {
                @Override
                protected void convert(@Nullable BaseViewHolder holder, int position, @Nullable final RelatedBean data)
                {
                    TextView count = holder.getView(R.id.tv_count);
                    Drawable drawable = App.getResource().getDrawable(R.mipmap.ic_play_count);
                    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                    count.setCompoundDrawables(drawable, null, null, null);
                    holder.setImageResource(R.id.img_game, data.getVideo_cover())
                            .setVisibility(R.id.img_video, View.VISIBLE)
                            .setVisibility(R.id.tv_count, View.GONE)
                            .setText(R.id.tv_title, data.getVideo_title())
                            .itemView.setOnClickListener(new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View view)
                        {
                            alert(data.getVideo_title());
                        }
                    });
                }
            };
        }
        return mRelatedAdapter;
    }

    /*评论标题*/
    public BaseDelegateAdapter getCommentsTitleAdapter()
    {
        if (mCommentsTitleAdapter == null)
        {
            mCommentsTitleAdapter = new BaseDelegateAdapter<CommentBean>(this, R.layout.layout_news_comments_title)
            {
                @Override
                protected void convert(@Nullable BaseViewHolder holder, int position, @Nullable CommentBean data)
                {
                    holder.setText(R.id.tv_count, (data != null && data.getInfo() != null) ? String.valueOf(data.getInfo().getCom_num()) : "0");
                }
            };
        }
        return mCommentsTitleAdapter;
    }

    /*评论*/
    public BaseDelegateAdapter getCommentsAdapter()
    {
        if (mCommentsAdapter == null)
        {
            mCommentsAdapter = new BaseDelegateAdapter<CommentBean.CommentDetailBean>(this, R.layout.layout_news_comments)
            {
                @Override
                protected void convert(@Nullable BaseViewHolder holder, int position, @Nullable CommentBean.CommentDetailBean data)
                {
                    holder.setCircleUserResource(R.id.img_user, data.getUser_img_center())
                            .setText(R.id.tv_user, data.getUsername())
                            .setText(R.id.tv_comments, data.getContents())
                            .setText(R.id.tv_time, TimeUtils.getNewsListTime(data.getCreated()))
                            .setText(R.id.tv_like, data.getComment_reply_total());
                }
            }.setIsEmpty(true);
        }
        return mCommentsAdapter;
    }


    @Override
    protected void onNewIntent(Intent intent)
    {
        super.onNewIntent(intent);

    }

    @Override
    public void share()
    {
        if (mShareUtils == null)
        {
            mShareUtils = new ShareUtils.Builder(this)
                    .setContentView(R.layout.window_share)
                    .build();
        }
        mShareUtils.show(LayoutInflater.from(this).inflate(R.layout.activity_news, null));
    }

    @Override
    public void report()
    {

    }

    @Override
    public void comments()
    {

    }

    @Override
    public void collect()
    {

    }

    @Override
    public void downloadVideo()
    {
        alert("开始下载...");
    }

    @Override
    protected void onDestroy()
    {
        if (mShareUtils != null)
        {
            mShareUtils.dismiss();
        }
        super.onDestroy();
    }
}
